<template>
  <div class="learn-container gradient-bg">
    <!-- 顶部进度条 -->
    <div class="header glass">
      <el-button @click="$router.back()" text>
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <div class="progress-info">
        <span>{{ currentIndex + 1 }} / {{ words.length }}</span>
        <el-progress 
          :percentage="progress" 
          :show-text="false" 
          style="width: 200px; margin-left: 10px"
        />
      </div>
      <el-button @click="toggleSound" text>
        <el-icon><Microphone /></el-icon>
        {{ soundEnabled ? '关闭' : '开启' }}发音
      </el-button>
    </div>

    <!-- 单词卡片区域 -->
    <div class="card-container">
      <transition name="slide" mode="out-in">
        <div 
          v-if="currentWord"
          :key="currentWord.id"
          class="word-card glass"
          :class="{ flipped: isFlipped }"
          @click="flipCard"
        >
          <!-- 正面：英文 -->
          <div class="card-front">
            <div class="word-main">
              {{ currentWord.word }}
            </div>
            <div class="phonetic">
              {{ currentWord.phonetic }}
            </div>
            <el-button 
              type="primary" 
              size="large"
              @click.stop="speakWord"
              :loading="speaking"
              circle
            >
              <el-icon size="30"><Microphone /></el-icon>
            </el-button>
            <div class="hint">点击卡片查看中文</div>
          </div>

          <!-- 背面：中文 -->
          <div class="card-back">
            <div class="chinese-main">
              {{ currentWord.chinese || '中文' }}
            </div>
            <div class="word-secondary">
              {{ currentWord.word || '单词' }}
            </div>
            <div class="unit-info">
              {{ currentWord.grade || '年级' }} · {{ currentWord.unit || '单元' }}
            </div>
            <div class="hint">点击卡片返回</div>
          </div>
        </div>
      </transition>

      <!-- 空状态 -->
      <div v-if="!currentWord && !loading" class="empty-state glass">
        <el-icon size="100" color="#999"><DocumentChecked /></el-icon>
        <h3>今日学习完成！</h3>
        <p>继续保持，明天再来吧~</p>
        <el-button type="primary" @click="$router.push('/dashboard')">
          返回首页
        </el-button>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="actions" v-if="currentWord">
      <el-button 
        size="large" 
        class="action-btn wrong"
        @click="markWord(false)"
        :loading="submitting"
      >
        <el-icon><Close /></el-icon>
        不认识
      </el-button>
      <el-button 
        size="large"
        class="action-btn know"
        type="success"
        @click="markWord(true)"
        :loading="submitting"
      >
        <el-icon><Check /></el-icon>
        认识
      </el-button>
    </div>

    <!-- 学习统计悬浮框 -->
    <div class="stats-float glass">
      <div class="stat-item">
        <span class="label">已学</span>
        <span class="value">{{ learnedCount }}</span>
      </div>
      <div class="stat-item">
        <span class="label">认识</span>
        <span class="value correct">{{ correctCount }}</span>
      </div>
      <div class="stat-item">
        <span class="label">不认识</span>
        <span class="value wrong">{{ wrongCount }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { vocabularyApi } from '@/api/vocabulary'
import { dashboardApi } from '@/api/dashboard'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Microphone, Check, Close, DocumentChecked } from '@element-plus/icons-vue'

const router = useRouter()

const words = ref<any[]>([])
const currentIndex = ref(0)
const isFlipped = ref(false)
const loading = ref(false)
const submitting = ref(false)
const speaking = ref(false)
const soundEnabled = ref(true)

const learnedCount = ref(0)
const correctCount = ref(0)
const wrongCount = ref(0)

const currentWord = computed(() => words.value[currentIndex.value])
const progress = computed(() => {
  if (words.value.length === 0) return 0
  return Math.round(((currentIndex.value + 1) / words.value.length) * 100)
})

// 语音合成
let speechSynthesis: SpeechSynthesis | null = null
let speechUtterance: SpeechSynthesisUtterance | null = null

onMounted(async () => {
  // 初始化语音
  if ('speechSynthesis' in window) {
    speechSynthesis = window.speechSynthesis
  }

  // 加载单词
  await loadWords()
})

onUnmounted(() => {
  // 清理语音
  if (speechSynthesis) {
    speechSynthesis.cancel()
  }
})

// 加载单词列表
const loadWords = async () => {
  try {
    loading.value = true
    const res = await vocabularyApi.getWordsToLearn(10) // 每次学习10个单词
    if (res.success && res.data) {
      words.value = res.data
      console.log('加载的单词数据:', words.value)
      if (words.value.length > 0) {
        console.log('第一个单词:', words.value[0])
      }
      if (words.value.length === 0) {
        ElMessage.info('今日学习任务已完成！')
      }
    }
  } catch (error) {
    console.error('加载单词失败:', error)
    ElMessage.error('加载单词失败')
  } finally {
    loading.value = false
  }
}

// 翻转卡片
const flipCard = () => {
  isFlipped.value = !isFlipped.value
  console.log('卡片翻转状态:', isFlipped.value)
  console.log('当前单词:', currentWord.value)
}

// 朗读单词
const speakWord = () => {
  if (!speechSynthesis || !currentWord.value || !soundEnabled.value) return

  speaking.value = true

  // 取消之前的朗读
  speechSynthesis.cancel()

  // 创建新的朗读
  speechUtterance = new SpeechSynthesisUtterance(currentWord.value.word)
  speechUtterance.lang = 'en-US'
  speechUtterance.rate = 0.8 // 语速
  speechUtterance.pitch = 1 // 音调
  
  speechUtterance.onend = () => {
    speaking.value = false
  }
  
  speechUtterance.onerror = () => {
    speaking.value = false
    ElMessage.warning('语音播放失败')
  }

  speechSynthesis.speak(speechUtterance)
}

// 切换发音开关
const toggleSound = () => {
  soundEnabled.value = !soundEnabled.value
  ElMessage.success(soundEnabled.value ? '已开启发音' : '已关闭发音')
}

// 标记单词
const markWord = async (know: boolean) => {
  if (!currentWord.value || submitting.value) return

  try {
    submitting.value = true

    // 提交学习记录
    const res = await vocabularyApi.recordProgress(currentWord.value.id, know)
    
    if (res.success) {
      // 更新统计
      learnedCount.value++
      if (know) {
        correctCount.value++
      } else {
        wrongCount.value++
      }

      // 显示反馈
      if (know) {
        ElMessage.success('太棒了！继续加油~')
      } else {
        ElMessage.info('没关系，多复习几次就记住了！')
      }

      // 自动朗读一次
      if (soundEnabled.value) {
        setTimeout(() => speakWord(), 300)
      }

      // 进入下一个单词
      setTimeout(() => {
        if (currentIndex.value < words.value.length - 1) {
          currentIndex.value++
          isFlipped.value = false
        } else {
          // 学习完成
          finishLearning()
        }
      }, 1000)
    }
  } catch (error) {
    console.error('提交记录失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 完成学习
const finishLearning = async () => {
  ElMessage.success({
    message: `🎉 完成学习！认识${correctCount.value}个，不认识${wrongCount.value}个`,
    duration: 3000
  })

  // 更新每日任务（暂时跳过错误，不影响用户体验）
  try {
    await dashboardApi.updateTaskProgress('learn_words')
  } catch (error) {
    console.log('更新任务失败（非关键错误）:', error.message)
    // 不显示错误信息给用户，因为学习已经完成
  }

  // 延迟返回首页
  setTimeout(() => {
    router.push('/dashboard')
  }, 2000)
}
</script>

<style scoped lang="scss">
.learn-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow-y: auto;
  overflow-x: hidden;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  
  .progress-info {
    display: flex;
    align-items: center;
    color: white;
    font-size: 1.1rem;
    font-weight: bold;
  }
}

.card-container {
  flex: 0 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  perspective: 1000px;
  min-height: 450px;
}

.word-card {
  width: 500px;
  height: 400px;
  position: relative;
  transform-style: preserve-3d;
  transition: transform 0.6s;
  cursor: pointer;
  background: transparent !important;
  backdrop-filter: none !important;
  
  &.flipped {
    transform: rotateY(180deg);
  }
  
  &.flipped .card-front {
    visibility: hidden;
  }
  
  &.flipped .card-back {
    visibility: visible;
  }
}

.word-card .card-front,
.word-card .card-back {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
  border: 1px solid rgba(255, 255, 255, 0.18);
}

.word-card .card-front {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  visibility: visible;
}

.word-card .card-front .word-main {
  font-size: 4rem;
  font-weight: bold;
  color: white;
  margin-bottom: 20px;
  text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

.word-card .card-front .phonetic {
  font-size: 1.8rem;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 40px;
}

.word-card .card-front .hint {
  margin-top: 40px;
  color: rgba(255, 255, 255, 0.6);
  font-size: 1rem;
}

.word-card .card-back {
  transform: rotateY(180deg);
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  visibility: hidden;
}

.word-card .card-back .chinese-main {
  font-size: 3.5rem;
  font-weight: bold;
  color: white;
  margin-bottom: 30px;
  text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

.word-card .card-back .word-secondary {
  font-size: 2rem;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 20px;
}

.word-card .card-back .unit-info {
  font-size: 1.2rem;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 20px;
}

.word-card .card-back .hint {
  margin-top: 20px;
  color: rgba(255, 255, 255, 0.6);
}

.empty-state {
  padding: 60px;
  text-align: center;
  border-radius: 20px;

  h3 {
    color: white;
    font-size: 2rem;
    margin: 20px 0;
  }

  p {
    color: rgba(255, 255, 255, 0.7);
    font-size: 1.2rem;
    margin-bottom: 30px;
  }
}

.actions {
  display: flex;
  justify-content: center;
  gap: 40px;
  padding: 10px 30px 30px;
  flex: 0 0 auto;

  .action-btn {
    width: 180px;
    height: 60px;
    font-size: 1.3rem;
    font-weight: bold;
    border-radius: 30px;
    transition: all 0.3s;

    &.wrong {
      background: linear-gradient(135deg, #f5576c 0%, #f093fb 100%);
      color: white;
      border: none;

      &:hover {
        transform: scale(1.05);
        box-shadow: 0 10px 30px rgba(245, 87, 108, 0.4);
      }
    }

    &.know {
      &:hover {
        transform: scale(1.05);
        box-shadow: 0 10px 30px rgba(103, 194, 58, 0.4);
      }
    }
  }
}

.stats-float {
  position: fixed;
  bottom: 30px;
  right: 30px;
  padding: 20px 30px;
  border-radius: 15px;
  display: flex;
  gap: 30px;

  .stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;

    .label {
      color: rgba(255, 255, 255, 0.7);
      font-size: 0.9rem;
      margin-bottom: 5px;
    }

    .value {
      color: white;
      font-size: 1.8rem;
      font-weight: bold;

      &.correct {
        color: #67c23a;
      }

      &.wrong {
        color: #f56c6c;
      }
    }
  }
}

// 动画
.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
}

.slide-enter-from {
  transform: translateX(100px);
  opacity: 0;
}

.slide-leave-to {
  transform: translateX(-100px);
  opacity: 0;
}

@media (max-width: 768px) {
  .learn-container {
    padding-bottom: 20px;
  }

  .card-container {
    min-height: 380px;
    padding: 10px;
  }

  .word-card {
    width: 90%;
    height: 320px;

    .card-front .word-main {
      font-size: 2.5rem;
    }

    .card-front .phonetic {
      font-size: 1.3rem;
      margin-bottom: 30px;
    }

    .card-back .chinese-main {
      font-size: 2.2rem;
    }

    .card-back .word-secondary {
      font-size: 1.5rem;
    }
  }

  .actions {
    gap: 20px;
    padding: 5px 20px 20px;

    .action-btn {
      width: 140px;
      height: 50px;
      font-size: 1.1rem;
    }
  }

  .stats-float {
    position: static;
    margin: 10px 20px 20px;
    justify-content: space-around;
  }
}
</style>

